package admin

import (
	"context"
	"github.com/asim/go-micro/v3"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"os"
	"server/models"
	Admin "server/proto/admin"
	"server/proto/product"
	"server/utils"
	"strconv"
	"time"
)

// AdminLogin godoc
//	@Summary		管理员登陆
//	@Description	管理员登陆
//	@Tags			管理员模块
//	@Accept			json
//	@Produce		json
//	@Param			username    formData     string  false  "username"  Format(email)
//  @Param			password    formData     string  false  "password"  Format(pass)
//	@Success		200		{object}  admin.AdminLoginResponse
//	@Failure		500		{object}  admin.AdminLoginResponse
//	@Router			/admin/login [post]
func Login(ctx *gin.Context) {
	// admin
	var admin models.AdminUser
	admin.UserName = ctx.PostForm("username")
	admin.PassWord = ctx.PostForm("password")

	service := micro.NewService()

	adminService := Admin.NewAdminService("develop_admin", service.Client())

	user := Admin.AdminLoginRequest{Username: admin.UserName, Password: admin.PassWord}

	rep, err := adminService.AdminLogin(context.TODO(), &user)
	if err != nil {
		ctx.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "用户登陆超时请重试",
		})
		return
	}

	//如果登陆成功 生成token
	token, err := utils.GenToken("admin", utils.AdminUserExpireDuration, utils.AdminUserSecretKey)
	if err != nil {
		log.Println("failed to GenToken:", err.Error())
	}

	ctx.JSON(http.StatusOK, gin.H{
		"code":        rep.Code,
		"msg":         rep.Message,
		"admin_token": token,
		"username":    "admin",
	})
}

// AllUser godoc
//	@Summary		查找所有用户
//	@Description	查找所有用户
//	@Tags			管理员模块
//	@Accept			json
//	@Produce		json
//	@Success		200		{object}  admin.AllUserResponse
//	@Failure		500		{object}  admin.AllUserResponse
//	@Router			/admin/AllUser [get]
func AllUser(ctx *gin.Context) {
	// 创建service
	service := micro.NewService()

	moduleService := Admin.NewAdminService("develop_admin", service.Client())

	rep, err := moduleService.AllUser(context.TODO(), &Admin.AllUserRequest{})
	if err != nil {
		ctx.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "获取用户列表失败",
		})
		return
	}
	ctx.JSON(http.StatusOK, gin.H{
		"code": rep.Code,
		"msg":  rep.Message,
		"data": rep.User,
	})

}

// DeleteUser godoc
//	@Summary		删除用户
//	@Description	删除用户
//	@Tags			管理员模块
//	@Accept			json
//	@Produce		json
//	@Param			name    formData     string  false  "name"  Format(name)
//	@Success		200		{object}  admin.AdminLoginResponse
//	@Failure		500		{object}  admin.AdminLoginResponse
//	@Router			/admin/DeleteUser [get]
func DeleteUser(ctx *gin.Context) {
	//获取用户提交的姓名
	name := ctx.Query("name")

	service := micro.NewService()

	adminService := Admin.NewAdminService("develop_admin", service.Client())

	rep, err := adminService.DeleteUser(context.TODO(), &Admin.DeleteUserRequest{Name: name})
	if err != nil {
		ctx.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "删除用户失败",
		})
		return
	}
	ctx.JSON(http.StatusOK, gin.H{
		"code": rep.Code,
		"msg":  rep.Message,
	})
}

// AddProduct godoc
//	@Summary		商品增加
//	@Description	商品增加
//	@Tags			管理员模块
//	@Accept			json
//	@Produce		json
//	@Param			name    formData     string  false  "name"  Format(name)
//	@Param			price    formData     string  false  "price"  Format(price)
//	@Param			desc    formData     string  false  "desc"  Format(desc)
//	@Param			address    formData     string  false  "address"  Format(address)
//	@Param			num    formData     string  false  "num"  Format(num)
//	@Param			pic    formData     string  false  "pic"  Format(pic)
//	@Success		200		{object}  product.AddProductResponse
//	@Failure		500		{object}  product.AddProductResponse
//	@Router			/admin/AddProduct [post]
func AddProduct(ctx *gin.Context) {
	name := ctx.PostForm("name")

	price := ctx.PostForm("price")

	desc := ctx.PostForm("desc")

	address := ctx.PostForm("address")

	num := ctx.PostForm("num")

	file, err := ctx.FormFile("pic")

	var file_path string

	if err != nil { //发生错误 不保存图片

		file_path = "upload/normal.jpg" //如果没有图片则用这张

	} else {
		unix_int64 := time.Now().Unix()

		unix_str := strconv.FormatInt(unix_int64, 10)

		file_path = "upload/" + unix_str + file.Filename

		ctx.SaveUploadedFile(file, file_path)
	}

	service := micro.NewService()

	productService := product.NewProductService("develop_admin", service.Client())

	rep, err := productService.AddProduct(context.TODO(), &product.AddProductRequest{
		Name:    name,
		Price:   price,
		Num:     num,
		Address: address,
		Desc:    desc,
		Pic:     file_path,
	})
	if err != nil {
		ctx.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "增加商品失败",
		})
		return
	}
	ctx.JSON(http.StatusOK, gin.H{
		"code": rep.Code,
		"msg":  rep.Msg,
	})

}

// showProduct godoc
//	@Summary		展示商品
//	@Description	展示商品
//	@Tags			管理员模块
//	@Accept			json
//	@Produce		json
//	@Success		200		{object}  product.ShowProductResponse
//	@Failure		500		{object}  product.ShowProductResponse
//	@Router			/admin/showProduct [get]
func ShowProduct(ctx *gin.Context) {
	service := micro.NewService()

	productService := product.NewProductService("develop_admin", service.Client())

	rep, err := productService.ShowProduct(context.TODO(), &product.ShowProductRequest{})
	if err != nil {
		ctx.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "获取商品信息失败",
		})
		return
	}
	ctx.JSON(http.StatusOK, gin.H{
		"code":     rep.Code,
		"msg":      rep.Msg,
		"products": rep.Products,
	})

}

// DeleteProduct godoc
//	@Summary		商品删除
//	@Description	商品删除
//	@Tags			管理员模块
//	@Accept			json
//	@Produce		json
//	@Param			name    formData     string  false  "name"  Format(name)
//	@Param			price    formData     string  false  "price"  Format(price)
//	@Param			desc    formData     string  false  "desc"  Format(desc)
//	@Param			address    formData     string  false  "address"  Format(address)
//	@Param			num    formData     string  false  "num"  Format(num)
//	@Param			pic    formData     string  false  "pic"  Format(pic)
//	@Success		200		{object}  product.AddProductResponse
//	@Failure		500		{object}  product.AddProductResponse
//	@Router			/admin/deleteProduct [post]
func DeleteProduct(ctx *gin.Context) {
	name := ctx.PostForm("name")

	price := ctx.PostForm("price")

	desc := ctx.PostForm("desc")

	address := ctx.PostForm("address")

	num := ctx.PostForm("num")

	pic := ctx.PostForm("pic")

	//首先删除该文件的图片
	if pic != "upload/normal.jpg" {
		os.Remove(pic)
	}
	service := micro.NewService()

	productService := product.NewProductService("develop_admin", service.Client())

	rep, err := productService.DeleteProduct(context.TODO(), &product.AddProductRequest{
		Name:    name,
		Price:   price,
		Num:     num,
		Address: address,
		Desc:    desc,
		Pic:     pic,
	})
	if err != nil {
		ctx.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "删除商品失败",
		})
		return
	}
	ctx.JSON(http.StatusOK, gin.H{
		"code": rep.Code,
		"msg":  rep.Msg,
	})
}

// SearchProduct godoc
//	@Summary		搜索商品
//	@Description	搜索商品
//	@Tags			管理员模块
//	@Accept			json
//	@Produce		json
//	@Param			name    formData     string  false  "name"  Format(name)
//	@Success		200		{object}  product.ShowProductResponse
//	@Failure		500		{object}  product.ShowProductResponse
//	@Router			/admin/searchProduct [post]
func SearchProduct(ctx *gin.Context) {
	name := ctx.PostForm("name")

	service := micro.NewService()

	productService := product.NewProductService("develop_admin", service.Client())

	rep, err := productService.SearchProduct(context.TODO(), &product.SearchProductRequest{Name: name})
	if err != nil {
		ctx.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "搜索用户失败",
		})
		return
	}
	ctx.JSON(http.StatusOK, gin.H{
		"code":     rep.Code,
		"msg":      rep.Msg,
		"products": rep.Products,
	})
}

// ShowAllOrder godoc
//	@Summary		展示所有商品
//	@Description	展示所有商品
//	@Tags			管理员模块
//	@Accept			json
//	@Produce		json
//	@Success		200		{object}  admin.ShowAllOrderResponse
//	@Failure		500		{object}  admin.ShowAllOrderResponse
//	@Router			/admin/showAllOrder [get]
func ShowAllOrder(ctx *gin.Context) {
	service := micro.NewService()

	adminService := Admin.NewAdminService("develop_admin", service.Client())

	rep, err := adminService.ShowAllOrder(context.TODO(), &Admin.AllUserRequest{})
	if err != nil {
		ctx.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "展示所有商品失败",
		})
		return
	}

	ctx.JSON(http.StatusOK, gin.H{
		"code":  rep.Code,
		"msg":   rep.Msg,
		"order": rep.Order,
	})
}

// Feedback godoc
//	@Summary		获取用户反馈
//	@Description	获取用户反馈
//	@Tags			管理员模块
//	@Accept			json
//	@Produce		json
//	@Success		200		{object}  admin.ShowUserBackedResponse
//	@Failure		500		{object}  admin.ShowUserBackedResponse
//	@Router			/admin/feedback [get]
func Feedback(ctx *gin.Context) {
	service := micro.NewService()

	adminService := Admin.NewAdminService("develop_admin", service.Client())

	rep, err := adminService.ShowUserBacked(context.TODO(), &Admin.ShowUserBackedRequest{})
	if err != nil {
		ctx.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "获取用户反馈失败",
		})
		return
	}

	ctx.JSON(http.StatusOK, gin.H{
		"code":     rep.Code,
		"msg":      rep.Msg,
		"feedback": rep.Feedback,
	})
}
